﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Security.Claims;
using System.Threading.Tasks;
using Von.Web.Datas;
using Von.Web.Structs;
using Von.Web.Models;
using Von.Web.Tasks;
using System.Threading;
using log4net;
using log4net.Repository;
using Von.Web.Interfaces;
/*
* Init() ->InitPortalSetting,InitAppSetting
*      InitAppSetting()->loop("*Application.json") {
*          AddFileListener,
*          loadAppAsync(load base info and memory settings),
*          Memory app to Applications,
*          ImportModule 
*      }
*      ImportModule{
*          ImportViewPart,
*          AddApplicationPart,
*              Loop(WebControllerBase.Actions, Memory actions to applicaton.Actions)
*          foreach(app in applications(from database))
*              ImportActions{
*                  Loop(WebControllerBase.Actions, Memory actions to applicaton.Actions)
*              }
*      }
* */
namespace Von.Web.Framework
{
    /// <summary>
    /// 平台运行库，系统加载和系统设置在这里完成
    /// </summary>
    public static class Runtime
    {
        #region Properties
        private static string _AppPath = null;
        public static string AppPath { get { if (_AppPath == null) _AppPath = Directory.GetCurrentDirectory() + "\\"; return _AppPath; } }
        public static ApplicationDefinationBase Portal = null;
        public static string defaultLogo { get => Portal.readJsonData(Portal.AppSetting, "Logo", "JamesVon").ToString(); }
        public static string defaultLayoutName { get => Portal.readJsonData(Portal.AppSetting, "Layout", "/wwwroot/Skins/MS_Layout/_Ms_Layout.cshtml").ToString(); }
        public static string adminLayoutName { get => Portal.readJsonData(Portal.AppSetting, "AdminLayout", "/wwwroot/Skins/Admin_Layout/AdminLayout.cshtml").ToString(); }
        public static string adminPanelName { get => Portal.readJsonData(Portal.AppSetting, "AdminLayout", "/wwwroot/Skins/Admin_Layout/AdminPanel.cshtml").ToString(); }
        public static string HomePage { get => Portal.readJsonData(Portal.AppSetting, "HomePage", "/Admin/Index").ToString(); }
        /// <summary>
        /// MVC服务接口
        /// </summary>
        public static IMvcBuilder mvcBuilder { get; set; }
        /// <summary>
        /// 系统服务接口
        /// </summary>
        public static ServiceProvider serviceProvider { get; set; }
        public static CompiledRazorAssemblyApplicationPartFactory razorPartFactory = new CompiledRazorAssemblyApplicationPartFactory();
        #endregion
        #region Log
        private static ILoggerRepository LogRepository = LogManager.CreateRepository("NETCoreRepository");
        private static ILog _Log = null;
        public static ILog Log
        {
            get
            {
                if (_Log == null)
                {
                    _Log = LogManager.GetLogger(LogRepository.Name, "VonWeb");
                }
                return _Log;
            }
        }
        private static LogTask _LogTask = null;
        public static LogTask LogTask
        {
            get
            {
                if (_LogTask == null)
                {
                    _LogTask = new LogTask();
                }
                return _LogTask;
            }
        }
        public static ILog CreateLog(Type T)
        {
            return LogManager.GetLogger(Runtime.LogRepository.Name, T);
        }
        #endregion
        #region 加载系统
        /// <summary>
        /// APPSetting信息
        /// </summary>
        private static List<AssemblyDefinationBase> AssemblyDefinations = new List<AssemblyDefinationBase>();
        private static List<ApplicationDefinationBase> Applications = new List<ApplicationDefinationBase>();
        public static List<ApplicationDefinationBase> ListApplication()
        {
            return Applications;
        }
        public static ApplicationDefinationBase GetApplication(Guid ID)
        {
            return Applications.FirstOrDefault(a => a.ID == ID);
        }
        public static void UpdateApplication(ApplicationDefinationBase app)
        {
            string settingFilename = Directory.GetCurrentDirectory() + "\\AppSettings.json";
            if (app != Portal) settingFilename = AppPath + "Bin\\" + app.AssemlyName + "Application.json";
            if (!File.Exists(settingFilename)) throw new Exception("配置文件不存在");
            JObject json = Von.Library.Functions.LoadJsonFile(settingFilename);
            json["AppName"] = app.AppName;
            json["AppTitle"] = app.AppTitle;
            json["WorkPath"] = app.WorkPath;
            json["DBConnectString"] = app.DBConnectString;
            json["Prefix"] = app.Prefix;
            json["Owner"] = app.Owner;
            json["Qualifier"] = app.Qualifier;
            json["LogClass"] = app.LogClass;
            json["Cert"] = app.Cert;
            json["Settings"] = app.AppSetting;
            int i = 1;
            while (File.Exists(settingFilename + "." + i.ToString())) i++;
            File.Move(settingFilename, settingFilename + "." + i.ToString());
            Von.Library.Functions.SaveJsonFile(json, settingFilename);
        }
        public static void RegistApplication(ApplicationDefinationBase app)
        {
            var A = Applications.FirstOrDefault(a => a.ID == app.ID);
            if (A == null) Applications.Add(app);
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public static void Load()
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            //加载log4net日志配置文件
            log4net.Config.XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));
            Log.Info("Initiate portal ... ...");
            //加载Portal
            AssemblyDefinationBase portalAssembly = new Statement();
            AssemblyDefinations.Add(portalAssembly);
            Applications.Add(portalAssembly.AppDefination);
            Portal = portalAssembly.AppDefination;
            InitPortalSetting(Portal); //初始化系统设置和所有的应用设置，同时开始监听所有配置文件的变动，一旦变动，系统会重新加载
            Statement.Accession.AppDefination = Portal;
            foreach (string s in portalAssembly.Imports)
            {
                Assembly assemlyImporter = AssemblyLoadContext.Default.LoadFromAssemblyPath(Directory.GetCurrentDirectory() + s + ".dll");
                mvcBuilder.AddApplicationPart(assemlyImporter);   // .dll 需要通过 AddApplicationPart 来加载
            }
            //portalAssembly.Init();
            Log.Info("Initiate application ... ...");
            //加载其他应用，应用设定信息存储在系统 BIN 目录中，以 *Application.json 为文件名，前面为应用名称
            var settingFiles = Directory.EnumerateFiles(AppPath + "Bin\\", "*Application.json", SearchOption.AllDirectories);
            foreach (string filename in settingFiles)
                try
                {
                    string s = Path.GetFileNameWithoutExtension(filename);
                    InitAppSetting(s.Substring(0, s.Length - 11));
                }
                catch (Exception ex)
                {
                    Log.Error("系统在加载" + filename.ToString() + "应用时出现异常：" + ex.Message);
                }
            sw.Stop();
            Log.Info($"Initiate service ... ...{sw.Elapsed.TotalMilliseconds}");
        }
        public static void Init()
        {
            foreach (AssemblyDefinationBase ass in AssemblyDefinations)
            {
                ass.Init();
            }
            InitService();      //启动系统进程，系统服务
        }
        /// <summary>
        /// 以配置文件信息初始化应用信息
        /// </summary>
        /// <param name="app"></param>
        private static void configApplication(ApplicationDefinationBase app, JObject setting)
        {
            app.ID = new Guid(setting["ID"].ToString());
            app.AppName = app.readJsonData(setting, "AppName", "").ToString();
            app.AppTitle = app.readJsonData(setting, "AppTitle", "").ToString();
            app.WorkPath = app.readJsonData(setting, "WorkPath", "").ToString();
            app.DBConnectString = app.readJsonData(setting, "DBConnectString", "").ToString();
            app.Prefix = app.readJsonData(setting, "Prefix", "").ToString();
            app.Owner = app.readJsonData(setting, "Owner", "").ToString();
            app.Qualifier = app.readJsonData(setting, "Qualifier", "").ToString();
            app.LogClass = (int)app.readJsonData(setting, "LogClass", 0);
            app.Cert = app.readJsonData(setting, "Cert", "").ToString();
            app.AppSetting = (JObject)app.readJsonData(setting, "Settings", new JObject());
        }
        /// <summary>
        /// 加载平台及所有应用配置信息
        /// </summary>
        /// <returns></returns>
        private static void InitPortalSetting(ApplicationDefinationBase app)
        {
            // 加载系统设定信息，在系统根目录中，文件名为 AppSettings.json
            string settingFilename = Directory.GetCurrentDirectory() + "\\AppSettings.json";
            // 加载配置文件信息
            JObject json = Von.Library.Functions.LoadJsonFile(settingFilename);
            configApplication(app, json);
            //merageApplication(app);
            ImportActions(app, (TypeInfo)typeof(Controllers.AdminController));
            ImportActions(app, (TypeInfo)typeof(Controllers.AccountController));
            ImportActions(app, (TypeInfo)typeof(Controllers.HomeController));
        }
        /// <summary>
        /// 加载平台及所有应用配置信息
        /// </summary>
        /// <returns></returns>
        public static Assembly InitAppSetting(string assemlyName)
        {
            #region 加载配置文件，加载页面文件，加载应用程序
            string filename = AppPath + "Bin\\" + assemlyName + "Application.json";
            if (!File.Exists(filename)) throw new Exception("配置文件不存在");
            JObject json = Von.Library.Functions.LoadJsonFile(filename);
            Guid appIdx = Guid.Parse(json["ID"].ToString());

            filename = AppPath + "Bin\\" + assemlyName + "Application.Views.dll";
            if (File.Exists(filename))
                importViewPart(mvcBuilder, razorPartFactory, filename);
            filename = AppPath + "Bin\\" + assemlyName + "Application.dll";
            importPart(mvcBuilder, filename);
            if (!File.Exists(filename)) throw new Exception("应用声明不存在");
            #endregion
            #region 加载App信息
            Assembly assemly = AssemblyLoadContext.Default.LoadFromAssemblyPath(filename);
            //mvcBuilder.AddApplicationPart(assemly);   // .dll 需要通过 AddApplicationPart 来加载
            TypeInfo statememtType = assemly.DefinedTypes.FirstOrDefault(a => a.BaseType != null && a.BaseType.Name == "AssemblyDefinationBase");
            if (statememtType == null) return null;
            AssemblyDefinationBase appStatement = (AssemblyDefinationBase)ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, statememtType);
            AssemblyDefinations.Add(appStatement);
            configApplication(appStatement.AppDefination, json);
            //merageApplication(appStatement.AppDefination);
            appStatement.AppDefination.AssemlyName = assemlyName;
            foreach (string s in appStatement.Imports)
            {
                Assembly assemlyImporter = AssemblyLoadContext.Default.LoadFromAssemblyPath(AppPath + s);
                mvcBuilder.AddApplicationPart(assemlyImporter);   // .dll 需要通过 AddApplicationPart 来加载
            }
            Applications.Add(appStatement.AppDefination);
            #endregion
            #region 加载控制层类和actions
            foreach (TypeInfo t in assemly.DefinedTypes)
            {
                if (t.BaseType != null && t.BaseType.Name == "WebControllerBase")
                {
                    WebControllerBase ctrl = (WebControllerBase)ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, t);
                    if (ctrl == null) throw new Exception("Can not found controller from assmebly " + assemlyName);
                    ImportActions(appStatement.AppDefination, t);
                    //LoadTable(app);
                }
                if (t.GetInterface("IInitiation") != null)
                {
                    IInitiation ctrl = (IInitiation)ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, t);
                    ctrl.init();
                }
                Log.Info("Initiate " + appStatement.AppDefination.AppName + " application add " + appStatement.AppDefination.Actions.Count + " actions.");
            }
            #endregion
            //appStatement.Init();
            return assemly;
        }
        /// <summary>
        /// 引入程序集
        /// </summary>
        /// <param name="assembly"></param>
        public static void ImportActions(ApplicationDefinationBase app, TypeInfo t)
        {
            string areaName = "";
            foreach (object attribute in t.GetCustomAttributes(true)) //2.通过映射，找到成员属性上关联的特性类实例，
            {
                if (attribute is AreaAttribute)//3.如果找到了限定长度的特性类对象，就用这个特性类对象验证该成员
                {
                    areaName = ((AreaAttribute)attribute).RouteValue;
                    break;
                }
            }
            string s = t.Name.Substring(t.Name.LastIndexOf('.') + 1);
            string ctrlName = s.IndexOf("Controller") > 0 ? s.Substring(0, s.IndexOf("Controller")) : s;
            foreach (MethodInfo method in t.GetMethods())
            {
                foreach (object attribute in method.GetCustomAttributes(true)) //2.通过映射，找到成员属性上关联的特性类实例，
                {
                    if (attribute is ActionAttribute)//3.如果找到了限定长度的特性类对象，就用这个特性类对象验证该成员
                    {
                        ActionAttribute attr = (ActionAttribute)attribute;
                        app.Actions.Add(new WebActionInfo(attr.ID, attr.ModuleName, areaName, ctrlName, method.Name, attr.ActionName, attr.ControlKind));
                    }
                }
            }
            app.Actions.Sort((x, y) => String.Compare(x.ModuleName + "-" + x.ActionName, y.ModuleName + "-" + y.ActionName, StringComparison.Ordinal));
        }
        /// <summary>
        /// 加载视图文件
        /// </summary>
        /// <param name="mvcBuilder"></param>
        /// <param name="razorPartFactory"></param>
        /// <param name="filename"></param>
        private static void importViewPart(IMvcBuilder mvcBuilder, CompiledRazorAssemblyApplicationPartFactory razorPartFactory, string filename)
        {
            // .views.dll 需要通过 CompiledRazorAssemblyApplicationPartFactory 来加载

            Assembly a = AssemblyLoadContext.Default.LoadFromAssemblyPath(filename);
            var viewAssemblyPart = new CompiledRazorAssemblyPart(a);
            mvcBuilder.PartManager.ApplicationParts.Add(viewAssemblyPart);
            return;
            mvcBuilder.ConfigureApplicationPartManager(manager =>
            {
                var lst = razorPartFactory.GetApplicationParts(a);
                foreach (var b in lst)
                    manager.ApplicationParts.Add(b);
            });
        }
        private static void importPart(IMvcBuilder mvcBuilder, string filename)
        {
            Assembly a = AssemblyLoadContext.Default.LoadFromAssemblyPath(filename);
            var assemblyPart = new AssemblyPart(a);
            mvcBuilder.PartManager.ApplicationParts.Add(assemblyPart);
            return;
            mvcBuilder.ConfigureApplicationPartManager(manager =>
            {
                manager.ApplicationParts.Add(assemblyPart);
            });
        }
        #endregion
        #region "System catching"
        private class catchModel<T> where T : class
        {
            public DateTime validTime { get; set; }
            public T obj { get; set; }
        }
        /// <summary>
        /// 资源文件读取器缓存
        /// </summary>
        private static List<catchModel<ResourceFileReader>> res = new List<catchModel<ResourceFileReader>>();
        /// <summary>
        /// 获取资源文件接口
        /// </summary>
        /// <param name="filename">资源文件名称</param>
        /// <returns></returns>
        public static ResourceFileReader GetResourceFileReader(string filename)
        {
            if (string.IsNullOrEmpty(filename)) return null;
            catchModel<ResourceFileReader> result = res.FirstOrDefault(s => s.obj.Filename.Equals(filename, StringComparison.OrdinalIgnoreCase));
            if (result == null && File.Exists(Directory.GetCurrentDirectory() + "\\wwwroot\\Resource\\" + filename + ".resources"))
            {
                ResourceFileReader reader = new ResourceFileReader(filename);
                if (string.IsNullOrEmpty(reader.Filename)) return null;
                result = new catchModel<ResourceFileReader>() { obj = reader, validTime = DateTime.Now.AddHours(24) };
                res.Add(result);
            }
            if (result == null) return null;
            return result.obj;
        }
        ///// <summary>
        ///// 人员信息缓存
        ///// </summary>
        //private static List<catchModel<IdentityUserInfo>> users = new List<catchModel<IdentityUserInfo>>();
        ///// <summary>
        ///// 获取登录人员信息（建立登录人员信息缓存）
        ///// </summary>
        ///// <param name="userID"></param>
        ///// <returns></returns>
        //public static IdentityUserInfo GetIdentityUserInfo(Guid userID)
        //{
        //    catchModel<IdentityUserInfo> result = users.FirstOrDefault(u => u.obj.ID.Equals(userID));
        //    if (result == null)
        //    {
        //        IdentityUserTask task = new IdentityUserTask();
        //        IdentityUserInfo user = task.GetByIdentity(userID).Result;//Task.Run(async () => await task.GetByIdentity(userID));
        //        if (user == null) return null;
        //        result = new catchModel<IdentityUserInfo>() { obj = user, validTime = DateTime.Now.AddHours(2) };
        //        users.Add(result);
        //    }
        //    else result.validTime = DateTime.Now.AddHours(2);
        //    return result.obj;
        //}
        ///// <summary>
        ///// 缓存登录人员信息
        ///// </summary>
        ///// <param name="user"></param>
        //public static void SetIdentityUserInfo(IdentityUserInfo user)
        //{
        //    catchModel<IdentityUserInfo> result = users.FirstOrDefault(u => u.obj.ID.Equals(user.ID));
        //    if (result == null)
        //    {
        //        result = new catchModel<IdentityUserInfo>() { obj = user, validTime = DateTime.Now.AddHours(2) };
        //        users.Add(result);
        //    } else {
        //        result.obj = user;
        //        result.validTime = DateTime.Now.AddHours(2);
        //    }
        //}
        #endregion
        #region "重要文件变动监控"
        /// <summary>
        /// 配置监听响应链堆栈
        /// </summary>
        private static Stack<KeyValuePair<string, FileSystemWatcher>> FileListeners = new Stack<KeyValuePair<string, FileSystemWatcher>>();
        /// <summary>
        /// 添加监听树节点
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        private static KeyValuePair<string, FileSystemWatcher> CreateListener(FileInfo info, FileSystemEventHandler e)
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.BeginInit();
            watcher.Path = info.DirectoryName;
            watcher.Filter = info.Name;
            watcher.IncludeSubdirectories = false;
            watcher.EnableRaisingEvents = true;
            watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size;
            watcher.Changed += e;
            watcher.EndInit();
            return new KeyValuePair<string, FileSystemWatcher>(info.FullName, watcher);
        }
        /// <summary>
        /// 添加文件监控
        /// </summary>
        /// <param name="filename">文件名，支持文件通配符</param>
        /// <param name="e">变动相应事件</param>
        private static void AddFileListener(string filename, FileSystemEventHandler e = null)
        {
            FileInfo config_info = new FileInfo(filename);
            FileListeners.Push(CreateListener(config_info, e ?? defaultFileSystemEventHandler));
        }
        private static void defaultFileSystemEventHandler(object sender, FileSystemEventArgs e)
        {
            string cmd = "";
            switch (e.ChangeType)
            {
                case WatcherChangeTypes.Created:
                    cmd = "Created"; break;
                case WatcherChangeTypes.Changed:
                    cmd = "Changed"; break;
                case WatcherChangeTypes.Deleted:
                    cmd = "Deleted"; break;
                case WatcherChangeTypes.Renamed:
                    cmd = "Renamed"; break;
            }
            JObject data = new JObject();
            data["path"] = e.FullPath;
            AppListen("FileMonitor", "Monitor", cmd, data);
        }
        #endregion
        #region Listeners
        private static List<listener> Listeners = new List<listener>();
        public static void RegisteListener(Guid appIdx, string senderName, EventOfListen listen)
        {
            Listeners.Add(new listener() { AppIdx = appIdx, Sender = senderName, Event = listen });
        }
        public static async Task AppListen(string senderName, string app, string cmdName, JObject data)
        {
            foreach (var l in Listeners)
            {
                if (l.Sender == senderName)
                {
                    if (await l.Event(app, cmdName, data)) return;
                }
            }
            return;
        }
        #endregion
        #region "Authentication"
        public static async Task<bool> checkRight(ClaimsPrincipal User, Guid actionID)
        {
            var s = User.FindFirstValue(ClaimTypes.NameIdentifier);
            Guid userID = string.IsNullOrEmpty(s) ? Guid.Empty : Guid.Parse(s);
            //判断模块有效期
            RightTask rightTask = new RightTask();
            List<RightInfo> lstRole = await rightTask.ListByDestIdx<RightInfo>(actionID);   //获取能够使用该功能的角色列表
            UserRoleTask userroleTask = new UserRoleTask();
            if (lstRole.Count == 0) return true;
            List<UserRoleInfo> roles = await userroleTask.ListByUser<UserRoleInfo>(userID);        //获取当前登录人拥有的角色
            return roles.Where(r => lstRole.FirstOrDefault(a => a.RoleName.Equals(r.RoleName)) != null).Count() > 0;
        }
        #endregion
        #region "Service"
        /// <summary>
        /// 系统服务缓存
        /// </summary>
        private static List<WebServiceBase> services = new List<WebServiceBase>();
        private static ServiceTask _svcTask = null;
        private static ServiceTask svcTask { get { if (_svcTask == null) _svcTask = new ServiceTask(); return _svcTask; } }
        public static List<WebServiceBase> ListService()
        {
            return services;
        }
        public static void RegistService(WebServiceBase svc)
        {
            var c = services.FirstOrDefault(i => i.ID == svc.ID);
            if (c != null) return;
            services.Add(svc);
            svcTask.GetServceModel(svc);
        }
        public static WebServiceBase GetService(Guid ID)
        {
            return services.FirstOrDefault(i => i.ID == ID);
        }
        public static void RemoveService(Guid ID)
        {
            var svc = services.FirstOrDefault(i => i.ID == ID);
            if (svc != null) return;
            svc.Status = "删除";
        }
        public static void SaveService(WebServiceBase svc)
        {
            svcTask.Save(svc);
        }
        public static void InitService()
        {
            Thread thread = new Thread(() =>
            {
                while (true)
                {
                    var svcs = services.Where(s => s.Status == "删除");
                    foreach (WebServiceBase svc in svcs)
                        services.Remove(svc);
                    Thread.Sleep(1000);
                    foreach (WebServiceBase svc in services)
                    {
                        //if (svc.Status == "启用") svc.nextTime = DateTime.Now.AddMinutes(- 1);
                        if (svc.Status == "启用" && svc.nextTime < DateTime.Now)
                        {
                            Log.Info(svc.ServiceName + " is run.");
                            try
                            {
                                if (svc.Necessary) svc.Run().Wait(); else svc.Run();
                            }
                            catch (Exception ex)
                            {
                                Log.Error("Service " + svc.ServiceName + " error:" + ex.Message);
                            }
                            svc.nextTime = svc.GetNextTime();
                        }
                    }
                }
            });
            //启动线程
            thread.Start();
        }
        #endregion
        #region "我的任务参数设置"
        static Dictionary<string, List<MyTaskSetting>> MyTaskSettings = new Dictionary<string, List<MyTaskSetting>>();
        public static void RegistMyTask(MyTaskSetting task)
        {
            var group = MyTaskSettings.FirstOrDefault(g => g.Key.Equals(task.TaskGroup, StringComparison.OrdinalIgnoreCase));
            List<MyTaskSetting> setting = null;
            if (default(KeyValuePair<string, List<MyTaskSetting>>).Equals(group))
            {
                setting = new List<MyTaskSetting>();
                MyTaskSettings.Add(task.TaskGroup, setting);
            }
            else setting = group.Value;
            setting.Add(task);
        }
        public static Dictionary<string, List<MyTaskInfo>> GetMyTask(Guid userId)
        {
            Dictionary<string, List<MyTaskInfo>> result = new Dictionary<string, List<MyTaskInfo>>();
            foreach (var ts in MyTaskSettings)
            {
                List<MyTaskInfo> tasks = new List<MyTaskInfo>();
                result.Add(ts.Key, tasks);
                foreach (var s in ts.Value)
                {
                    foreach (var c in s.Selection.conditions)
                    {
                        if (c.Data.ToString().Equals("@userid", StringComparison.OrdinalIgnoreCase))
                            c.Data = userId;
                    }
                    var lst = s.App.DBAccession.ListFromDB(s.Selection);
                    foreach (var l in lst)
                    {
                        MyTaskInfo info = new MyTaskInfo();
                        info.TaskName = s.TaskName;
                        info.Title = Von.Library.Functions.VonFormat(s.TitleFmt, l);
                        info.Url = Von.Library.Functions.VonFormat(s.UrlFmt, l);
                        tasks.Add(info);
                    }
                }
            }
            return result;
        }
        #endregion
        #region 大屏组件注册及管理
        private static List<ScreenComponentBase> lst = new List<ScreenComponentBase>();
        /// <summary>
        /// 组件注册
        /// </summary>
        /// <param name="cmp">组件</param>
        /// <returns></returns>
        public static bool RegistComponent(ScreenComponentBase cmp)
        {
            var c = lst.FirstOrDefault(i => i.ComponentName.Equals(cmp.ComponentName, StringComparison.OrdinalIgnoreCase));
            if (c == null)
            {
                lst.Add(cmp); return true;
            }
            return false;
        }
        /// <summary>
        /// 获取所有大屏组件名称列表
        /// </summary>
        /// <returns>大屏组件名称列表</returns>
        public static IEnumerable<string> ListComponent()
        {
            return lst.Select(i => i.ComponentName);
        }
        /// <summary>
        /// 根据组件名称得到对应的组件
        /// </summary>
        /// <param name="name">组件名称</param>
        /// <returns>大屏组件</returns>
        public static ScreenComponentBase GetComponent(string name)
        {
            return lst.FirstOrDefault(i => i.ComponentName.Equals(name, StringComparison.OrdinalIgnoreCase));
        }
        #endregion
    }
}